import json
from django.http import JsonResponse
from Web.WebClassCongregation import UserInfo,ActiveScanList
from Web.Workbench.Tasks import MedusaScan
from Web.Workbench.LogRelated import UserOperationLogRecord,RequestLogRecord
from ClassCongregation import ErrorLog,Proxies
from config import headers,proxies


#接收数据样式
'''vulnerability_scanning
{
	"url": "www.ascotbe.com",
	"token": "1EmWI2bgSWz477WQQMsgWidPSJmUiZy3B4VN0AYczjkdRs5fQvuhwOuek08bVSlzWV1HXf4fWupDgw8m9Lct4frZf5RqYPZBSvrXiIO3uvQ15FRNc8y5f1Rd8Y02CYQLF0BKW0S4qdmVo7k9yOGnpxHpGYfCYXfLi5ZRojsEHhevIEmeECSZL5awSXNWN9EyUQGjndoNoh5EZXxP4wstQA5JILjVldaqcfBElBgWJx4mKeZ9uFE9A4pI3i",
	"process": 200,
	"module": "all",
	"header": "",
	"proxy": "127.0.0.1:8080"
}
'''
##获取redis下发任务的Key，然后后台查询key来看是否工作完成，完成的话就查Medusa表然后写入ScanInformation表,到时候放到Tasks文件中
def Scan(request):
    RequestLogRecord(request, request_api="vulnerability_scanning")
    if request.method == "POST":
        try:
            ReceiveData=json.loads(request.body)
            ScanUrl=ReceiveData["url"]
            ScanToken= ReceiveData["token"]
            ScanModule = ReceiveData["module"]
            ScanProcess = ReceiveData["process"]
            ScanHeader = ReceiveData["header"]
            ScanProxy = ReceiveData["proxy"]
            if len(ScanProxy)>7:#如果传入的值不为空
                ScanProxy=Proxies().result(ScanProxy)
            else:
                ScanProxy=proxies

            if ScanHeader == "":  # Headers为空，就使用配置文件中的头
                ScanHeader = headers


            if type(ScanProcess)==int:#判断类型
                Uid=UserInfo().QueryUidWithToken(ScanToken)#如果登录成功后就来查询用户名
                if Uid!=None:
                    UserOperationLogRecord(request, request_api="vulnerability_scanning", uid=Uid)
                    ActiveScanId=ActiveScanList().Write(uid=Uid,url=ScanUrl,proxy=str(ScanProxy),status=0,module=ScanModule,process=ScanProcess)#写入用户关系表,然后返回sid下发给任务
                    RedisActiveScanTask= MedusaScan.delay(ScanUrl,ScanModule,ScanProcess,ScanHeader,ScanProxy,Uid,ActiveScanId)#调用扫描处理函数
                    ActiveScanList().UpdateRedisId(uid=Uid,active_scan_id=ActiveScanId,redis_id=RedisActiveScanTask.task_id)
                    return JsonResponse({'message': '任务下发成功👌', 'code': 200, })
                else:
                    return JsonResponse({'message': "小宝贝这是非法查询哦(๑•̀ㅂ•́)و✧", 'code': 403, })

            else:
                return JsonResponse({'message': '类型错误！', 'code': 666, })

        except Exception as e:
            ErrorLog().Write("Web_BasicFunctions_VulnerabilityScanning_Scan(def)", e)
            return JsonResponse({'message': '莎酱被玩坏掉嘞QAQ', 'code': 169, })
    else:
        return JsonResponse({'message': '请使用Post请求', 'code': 500, })


